// api.js - 模拟API请求
// 模拟API服务类
class ApiService {
    // 静态模拟数据存储
        static mockData = {
            // 模拟角色数据
            roles: [
                { id: 1, name: '超级管理员', description: '拥有系统所有权限', permissions: ['user_management', 'courier_management', 'package_management', 'role_management', 'exception_handling'] },
                { id: 2, name: '普通管理员', description: '负责日常运营管理', permissions: ['user_management', 'courier_management', 'package_management', 'exception_handling'] },
                { id: 3, name: '物流管理员', description: '负责物流人员和包裹管理', permissions: ['courier_management', 'package_management'] },
                { id: 4, name: '客服专员', description: '处理客户异常和投诉', permissions: ['exception_handling'] }
            ],
            // 模拟用户数据
            users: [
                { id: 1, username: 'user1', password: 'password1', role: 'user' },
                { id: 2, username: 'courier1', password: 'password1', role: 'courier' },
                { id: 3, username: 'admin1', password: 'password1', role: 'admin' }
            ],
            // 模拟包裹数据
            packages: [
                { id: 'PKG123456', status: 'pending', sender: '张三', receiver: '李四', origin: '北京', destination: '上海', currentLocation: '北京仓库', estimatedDelivery: '2023-12-15', courierId: 101, updates: [
                    { time: '2023-12-10 09:00', status: 'pending', location: '北京仓库', description: '订单已创建，等待发货' },
                    { time: '2023-12-10 10:30', status: 'pending', location: '北京仓库', description: '包裹已入库' }
                ]},
                { id: 'PKG654321', status: 'in-transit', sender: '王五', receiver: '赵六', origin: '广州', destination: '深圳', currentLocation: '广州至深圳途中', estimatedDelivery: '2023-12-12', courierId: 102, updates: [
                    { time: '2023-12-10 11:00', status: 'pending', location: '广州仓库', description: '订单已创建，等待发货' },
                    { time: '2023-12-10 13:00', status: 'in-transit', location: '广州仓库', description: '包裹已发出' },
                    { time: '2023-12-11 09:00', status: 'in-transit', location: '广州至深圳途中', description: '包裹在运输途中' }
                ]},
                { id: 'PKG987654', status: 'delivered', sender: '孙七', receiver: '周八', origin: '杭州', destination: '南京', currentLocation: '南京签收点', estimatedDelivery: '2023-12-09', actualDelivery: '2023-12-09', courierId: 103, updates: [
                    { time: '2023-12-07 14:00', status: 'pending', location: '杭州仓库', description: '订单已创建，等待发货' },
                    { time: '2023-12-07 16:00', status: 'in-transit', location: '杭州仓库', description: '包裹已发出' },
                    { time: '2023-12-08 10:00', status: 'in-transit', location: '杭州至南京途中', description: '包裹在运输途中' },
                    { time: '2023-12-09 09:30', status: 'delivered', location: '南京签收点', description: '包裹已送达，收件人周八签收' }
                ]}
            ],
            // 模拟物流员数据
            couriers: [
                { id: 101, name: '张物流', phone: '13800138001', currentPackages: 5, completedPackages: 45 },
                { id: 102, name: '李快递', phone: '13900139002', currentPackages: 8, completedPackages: 62 },
                { id: 103, name: '王速递', phone: '13700137003', currentPackages: 3, completedPackages: 78 }
            ],
            // 模拟管理员数据
            admins: [
                { id: 201, name: '管理员1', phone: '13600136001' },
                { id: 202, name: '管理员2', phone: '13500135002' }
            ]
        };

    constructor() {
        // 绑定this上下文
        this.fetch = this.fetch.bind(this);
    }

    // 模拟延迟
    static delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 认证相关API
    async login(username, password) {
        await this.delay(500);
        const user = this.mockData.users.find(u => u.username === username && u.password === password);
        if (user) {
            return {
                success: true,
                data: {
                    id: user.id,
                    username: user.username,
                    role: user.role,
                    token: `mock_token_${user.id}`
                }
            };
        } else {
            return {
                success: false,
                message: '用户名或密码错误'
            };
        }
    }

    async register(username, password, role) {
        await this.delay(500);
        const existingUser = this.mockData.users.find(u => u.username === username);
        if (existingUser) {
            return {
                success: false,
                message: '用户名已存在'
            };
        } else {
            const newId = this.mockData.users.length + 1;
            this.mockData.users.push({
                id: newId,
                username,
                password,
                role: role || 'user'
            });
            return {
                success: true,
                message: '注册成功'
            };
        }
    }

    // 包裹相关API
    async getPackageById(packageId) {
        await this.delay(500);
        const pkg = this.mockData.packages.find(p => p.id === packageId);
        if (pkg) {
            return {
                success: true,
                data: pkg
            };
        } else {
            return {
                success: false,
                message: '未找到包裹信息'
            };
        }
    }

    static async getAllPackages() {
        await this.delay(500);
        return {
            success: true,
            data: ApiService.mockData.packages
        };
    }

    async updatePackageStatus(packageId, status, location, description) {
        await this.delay(500);
        const pkg = this.mockData.packages.find(p => p.id === packageId);
        if (pkg) {
            pkg.status = status;
            pkg.currentLocation = location;
            if (status === 'delivered') {
                pkg.actualDelivery = new Date().toISOString().split('T')[0];
            }
            pkg.updates.push({
                time: new Date().toLocaleString(),
                status,
                location,
                description
            });
            return {
                success: true,
                message: '包裹状态更新成功'
            };
        } else {
            return {
                success: false,
                message: '未找到包裹信息'
            };
        }
    }

    // 角色相关API
    async getRoles() {
        await this.delay(500);
        // 检查是否存在角色数据存储
        if (!this.mockData.roles) {
            // 初始化角色数据（如果不存在）
            this.mockData.roles = [
                { id: 1, name: '超级管理员', description: '拥有系统所有权限', permissions: ['user_management', 'courier_management', 'package_management', 'role_management', 'exception_handling'] },
                { id: 2, name: '普通管理员', description: '负责日常运营管理', permissions: ['user_management', 'courier_management', 'package_management', 'exception_handling'] }
            ];
        }
        return {
            success: true,
            data: this.mockData.roles
        };
    }

    async getRoleById(roleId) {
        await this.delay(500);
        const role = this.mockData.roles.find(r => r.id === roleId);
        if (role) {
            return {
                success: true,
                data: role
            };
        } else {
            return {
                success: false,
                message: '未找到角色信息'
            };
        }
    }

    // 异常处理相关API
    async updateException(exceptionId, data) {
        await this.delay(500);
        // 检查是否存在异常数据存储
        if (!this.mockData.exceptions) {
            // 初始化异常数据（如果不存在）
            this.mockData.exceptions = [
                { id: 1, trackingNumber: 'PKG123456', type: 'delay', status: 'pending', description: '包裹因天气原因延迟配送', handlingNote: '', handledAt: null },
                { id: 2, trackingNumber: 'PKG654321', type: 'address_error', status: 'processing', description: '收件人地址不正确，需要确认', handlingNote: '已联系收件人确认地址', handledAt: '2023-12-11T08:30:00Z' }
            ];
        }
        
        const exception = this.mockData.exceptions.find(e => e.id == exceptionId);
        if (exception) {
            // 更新异常数据
            exception.type = data.type || exception.type;
            exception.status = data.status || exception.status;
            exception.description = data.description;
            exception.handlingNote = data.handlingNote;
            exception.handledAt = new Date().toISOString();
            
            return {
                success: true,
                message: '异常信息更新成功',
                data: exception
            };
        } else {
            return {
                success: false,
                message: '未找到异常信息'
            };
        }
    }

    // 物流员相关API
    async getCourierById(courierId) {
        await this.delay(500);
        const courier = this.mockData.couriers.find(c => c.id === courierId);
        if (courier) {
            return {
                success: true,
                data: courier
            };
        } else {
            return {
                success: false,
                message: '未找到物流员信息'
            };
        }
    }

    async getCourierPackages(courierId) {
        await this.delay(500);
        const packages = this.mockData.packages.filter(p => p.courierId === courierId);
        return {
            success: true,
            data: packages
        };
    }

    // 统计数据API
    async getDashboardStats() {
        await this.delay(500);
        const totalPackages = this.mockData.packages.length;
        const pendingPackages = this.mockData.packages.filter(p => p.status === 'pending').length;
        const inTransitPackages = this.mockData.packages.filter(p => p.status === 'in-transit').length;
        const deliveredPackages = this.mockData.packages.filter(p => p.status === 'delivered').length;

        return {
            success: true,
            data: {
                totalPackages,
                pendingPackages,
                inTransitPackages,
                deliveredPackages,
                couriersCount: this.mockData.couriers.length,
                usersCount: this.mockData.users.length
            }
        };
    }

    // 模拟API请求的fetch方法
    async fetch(url, options = {}) {
        // 解析URL以获取端点
        const parsedUrl = new URL(url, window.location.origin);
        const endpoint = parsedUrl.pathname;
        const method = options.method || 'GET';

        console.log('处理API请求:', endpoint, '方法:', method);

        try {
            // 根据不同的端点和方法处理请求
            if (endpoint === '/api/packages' && method === 'GET') {
                return await ApiService.getAllPackages();
            }
            else if (endpoint === '/api/stats/dashboard' && method === 'GET') {
                return await this.getDashboardStats();
            }
            else if (endpoint === '/api/auth/login' && method === 'POST') {
                const { username, password } = options.body || {};
                return await this.login(username, password);
            }
            else if (endpoint === '/api/auth/register' && method === 'POST') {
                const { username, password, role } = options.body || {};
                return await this.register(username, password, role);
            }
            else if (endpoint.startsWith('/api/packages/') && method === 'GET') {
                const packageId = endpoint.split('/').pop();
                return await this.getPackageById(packageId);
            }
            else if (endpoint === '/api/couriers' && method === 'GET') {
                return {
                    success: true,
                    data: ApiService.mockData.couriers
                };
            }
            else if (endpoint.startsWith('/api/couriers/') && method === 'GET') {
                const courierId = parseInt(endpoint.split('/').pop());
                return await this.getCourierById(courierId);
            }
            else if (endpoint.startsWith('/api/couriers/') && endpoint.endsWith('/packages') && method === 'GET') {
                const courierId = parseInt(endpoint.split('/')[3]);
                return await this.getCourierPackages(courierId);
            }
            else if (endpoint.startsWith('/api/packages/') && method === 'PUT') {
                const packageId = endpoint.split('/').pop();
                const { status, location, description } = options.body || {};
                return await this.updatePackageStatus(packageId, status, location, description);
            }
            else if (endpoint === '/api/roles' && method === 'GET') {
                return await this.getRoles();
            }
            else if (endpoint.startsWith('/api/roles/') && method === 'GET') {
                const roleId = parseInt(endpoint.split('/').pop());
                return await this.getRoleById(roleId);
            }
            else if (endpoint.startsWith('/api/exceptions/') && method === 'PUT') {
                const exceptionId = endpoint.split('/').pop();
                const data = options.body || {};
                return await this.updateException(exceptionId, data);
            }
            else {
                // 未匹配的端点
                return {
                    success: false,
                    message: `未找到端点: ${endpoint}`
                };
            }
        } catch (error) {
            console.error('API请求错误:', error);
            return {
                success: false,
                message: 'API请求发生错误'
            };
        }
    }
}

// 导出单例实例到全局作用域
window.apiService = new ApiService();

